<?php


namespace app\admin\model;


use app\common\model\TimeModel;
use think\facade\Db;
use think\facade\Log;
use think\Model;

class UserMoneyChange extends TimeModel
{

    public function user()
    {
        return $this->belongsTo('app\admin\model\UserBase', 'uid', 'id');
    }

    public function fromuser()
    {
        return $this->belongsTo('app\admin\model\UserBase', 'related_uid', 'id');
    }

    public function changetype()
    {
        return $this->belongsTo('app\admin\model\UserChangeType', 'change_type', 'id');
    }

    public static function onAfterRead(Model $model)
    {
        if (isset($model->change_type)) {//充值类型id变文字
            $model->type_name = UserChangeType::getTitleById($model->change_type);
        }
    }


    function moneyInc(int $uid, float $money, $change_type, $money_type = 1, int $related_uid = 0)
    {
        if ($money <= 0) return false;
        $change_type = is_string($change_type) ? UserChangeType::getIdByName($change_type) : $change_type;
        $data = [
            'uid' => $uid,
            'related_uid' => $related_uid,
            'money' => $money,
            'change_type' => $change_type,
            'money_type' => $money_type,
            'inc_or_dec' => 1
        ];
        return $this->moneyChange($data);
    }


    function moneyDec(int $uid, float $money, $change_type, $money_type = 1, int $related_uid = 0)
    {
        if ($money <= 0) return false;
        $change_type = is_string($change_type) ? UserChangeType::getIdByName($change_type) : $change_type;
        $data = [
            'uid' => $uid,
            'related_uid' => $related_uid,
            'money' => $money,
            'change_type' => $change_type,
            'money_type' => $money_type,
            'inc_or_dec' => 0
        ];
        return $this->moneyChange($data);
    }

    private function moneyChange($insert_data)
    {
        $has_field = 'has_money' . $insert_data['money_type'];
        $raw = $insert_data['inc_or_dec'] ? $has_field . '+' . $insert_data['money'] : $has_field . '-' . $insert_data['money'];
        $insert_data['before_money'] = UserBase::where('id', $insert_data['uid'])->value($has_field);
        Db::startTrans();
        try {
            UserBase::where('id', $insert_data['uid'])->update([
                $has_field => Db::raw($raw),
            ]);
            $this->save($insert_data);
            SystemFinanceDay::init()->updateFinance($insert_data['money'], $insert_data['change_type']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::write('资金更新失败：' . $e->getMessage() . json_encode($insert_data), 'moneyChange');
            return error('资金变动添加失败');
        }
        return success();
    }


}